var factoryTable = function() {
	var validator;
	return {
		init : function() {
			//初始化checkBox 初始化行点击选中
			var tableId = "factory_table";
			util.initCheckBox(tableId);
			function queryData(sSource, aoData, fnCallback) {
				aoData.push({
					"name" : "customName",
					"value" : $("#query_customName").val().trim()
				});
				aoData.push({
					"name" : "facName",
					"value" : $("#query_facName").val().trim()
				});
				$.ajax({	
					"type" : "post",
					"url" : sSource,
					"dataType" : "json",
					"data" : {
						"aoData" : JSON.stringify(aoData)
					},
					"success" : function(resp) {
						fnCallback(resp);
					}
				});
			};
			$('#factory_table').DataTable({
				"processing" : true,
				"serverSide" : true,
				"sAjaxSource" : "main/factory/getCustomFactories.mvc",
				"fnServerData" : queryData,
				"pageLength" : 10,
				"sDom" : "<'row-fluid'r>t<'row-fluid'<'span6'i><'span6'p>>",
				"oLanguage" : util.getDToLanguage(),
				"columns" : [ {
					"data" : "pkId",
					"render" : function(data, type, full, meta) {
						 return '<div class="checker" onclick="util.selectCheckBox(\'' + tableId + '\', this)"><span><input type="checkbox" class="checkboxes"/></span></div>';
					},
					"bSortable" : false
				},
				 
				{
					"data" : "customName",
					"bSortable" : false,
					"defaultContent": ""
				},
				{
					"data" : "parentCusName",
					"bSortable" : false,
					"defaultContent": ""
				},
				{
					"data" : "facName",
					"bSortable" : false,
					"defaultContent": "",
					"render" : function(data, type, full, meta) {
						 return '<a style="cursor:pointer;color:blue;" class="showFactoryDetail" data-toggle="modal">'+data+'</a>';
					}
				},
				{
					"data" : "area",
					"bSortable" : false,
					"defaultContent": ""
				},
				{
					"data" : "packNum",
					"bSortable" : false,
					"defaultContent": ""
				},
				{
					"data" : "parentCusId",
					"bSortable" : false,
					"visible" : false,  //隐藏列
					"defaultContent": ""
				}],
				"fnDrawCallback" : function(oSetting) {
					util.clearSelected(tableId);
				}
			});

			// 查询
			$("#btn_query").click(function(e) {
				var table = $('#factory_table').DataTable();
				table.draw(true);
			});
		    // 重置
			$("#btn_reset").click(function(e) {
				$("#query_customName").val("");
				$("#query_facName").val("");
			});
			
			//新增点击事件
			$("#factory_table_add").click(function() {
				$('#addFactory_title').text('新增厂区');
				$.ajax({  
			           type: 'POST',  
			           url:  "main/cusContacts/getCustomers.mvc", //url    
			           dataType: "json",   //可以是text，如果用text，返回的结果为字符串；如果需要json格式的，可是设置为json  
			           ContentType: "application/json; charset=utf-8",  
			           success: function (resp) {
			        	 //初始化省市联动下拉框
			   			 $("#cityDiv").citySelect({  
			   				  nodata: "none",  
			   			      required: true,  
			   			      prov:"北京",  
			   			      city:"东城区",  
			   			      dist:""  
			   			 }); 
			   			 debugger;
			   			 util.initSelect("#customId");
			   			 var data = resp.data;
			           	 $.each(data,function(index,value){
		          		     $('#customId').append('<option value="' + data[index].key+ '">'+data[index].value+'</option>');
		          		 });
		          		 $("#parentCusName").attr({"disabled":"disabled"});
			           	 $("#add-factory").modal({show:true, keyboard:false});
			           },  
			           error: function (msg) {  
			        	   util.showModal("#_alertModal", "获取所属客户失败！");
			           }  
				});
			});
 
			$("#customId").change(function(e) {
				var cusId = $(this).children('option:selected').val();
				$.ajax({
					"type" : "post",
					"url" : "main/customer/getCustomerById.mvc",
					"dataType" : "json",
					"data" : {
						"pkId" : cusId
					},
					"success" : function(data) {
						if(data){
							$("#parentCusId").val(data.parentCusId);
							$("#parentCusName").val(data.parentCusName);
						}
					}
				}); 
			});
			
			//保存按钮点击事件
			$("#form_factory_save").click(function(){
				validator = validateMyForm("factory_form");
				if(validator.form()){
					save();
				}else{
					return false;
				}
			});
			
			
			//validate 自定义验证
			function validateMyForm(formId){
				return $( '#' + formId ).validate({  
					errorElement: 'em',
					focusInvalid: false, 
					ignore: "",
			        rules:{  
			        	customId:'required',
			        	facName:'required',
			        	zipCode:'checkZipCode'
			            },  
			        messages:{  
			        	customId:'客户不能为空',
			        	facName:'厂区不能为空',
			        	zipCode:'邮编非法'
			            }, 
			            errorPlacement: function (error, element) { 
			            	//默认以span形式显示在输入框后
		                   error.insertAfter(element);
		                   $(element.next()).attr('title', $(error).text()).tooltip();
		                   $(error).text('');
		                }
			    });  
			};
			$.validator.addMethod("checkZipCode",function(value,element,params){  
	            var checkZipCode = /^[0-9][0-9]{5}$/;  
	            return this.optional(element)||(checkZipCode.test(value));  
	        });
			
			//保存
			function save(){
				var factory = {};
				factory['pkId'] = $("#pkId").val();
				factory['customId'] = $("#customId").val();
				factory['facName'] = $("#facName").val();
				factory['province'] = $("#province").find("option:selected").text();
				factory['city'] = $("#city").find("option:selected").text();
				factory['area'] = $("#area").find("option:selected").text();
				factory['zipCode'] = $("#zipCode").val();
				factory['address'] = $("#address").val();
				var table = $('#factory_table').DataTable();
				var currentPage =table.page();
				$.ajax({
					"type" : "post",
					"url" : "main/factory/saveOrUpdateCustomFactory.mvc",
					"dataType" : "json",
					"data" : factory,
					"success" : function(resp) {
						$("#form_btn_close").click();
						//table.draw(true);
						table.page(currentPage).draw('page');
						rmsBox.notify('success', {msg: '操作成功！'});
					},
					"error" : function(resp) {
						rmsBox.notify('error', {msg: '操作失败！',delay:3000});
					}
				});
			};
			
			// 编辑按钮点击
			$('#factory_table_edit').click(function() {
				var factory = [];
				factory = util.getCheckedData("factory_table");
				if (factory.length != 1) {
					util.showModal("#_alertModal", "请选择一条记录进行操作！");
					return false;
				}
				$('#addFactory_title').text('编辑厂区');
				$.ajax({
					"type" : "post",
					"url" : "main/factory/initCustomFactoryEdit.mvc",
					"dataType" : "json",
					"data" : {id:factory[0].pkId},
					"success" : function(data) {
						var factory = data.factory;
						var cusDict = data.cusDict;
						util.initSelect("#customId");
						$.each(cusDict,function(index,value){
							$('#customId').append('<option value="' + cusDict[index].value+ '">'+cusDict[index].name+'</option>');
		          		});
						$("#pkId").val(factory.pkId);
						$("#customId").val(factory.customId);
						$("#facName").val(factory.facName);
						$("#cityDiv").citySelect({ 
							nodata: "none",  
					        required: true,
						    prov: factory.province, //省份 
						    city: factory.city, //城市
						    dist: factory.area
						}); 
						$("#address").val(factory.address);
						$("#zipCode").val(factory.zipCode);
						$("#parentCusName").attr({"disabled":"disabled"});
						$("#add-factory").modal({show:true, keyboard:false});
					},
					"error" : function(resp) {
						util.showModal("#_alertModal", "获取厂区信息失败！");
					}
				});

				
			});
			
			//详情点击事件
			$('#factory_table').on('click','a.showFactoryDetail', function(e) {
				var factory = [];
				factory = util.getCheckedData("factory_table");
				$.ajax({
					"type" : "post",
					"url" : "main/factory/getCustomFactoryDetail.mvc",
					"dataType" : "json",
					"data" : {id:factory[0].pkId},
					"success" : function(data) {
						$("#detail_customName").text(data.customName);
						$("#detail_customName").attr('title', data.customName);
						$("#detail_facName").text(data.facName);
						$("#detail_facName").attr('title', data.facName);
						$("#detail_province").text(data.province);
						$("#detail_city").text(data.city);
						$("#detail_area").text(data.area);
						$("#detail_address").text(data.address);
						$("#detail_address").attr('title', data.address);
						$("#detail_zipCode").text(data.zipCode);
						$("#detail-factory").modal("show");
						$("#detail-factory").modal({show:true, keyboard:false});
					},
					"error" : function(resp) {
						util.showModal("#_alertModal", "获取厂区信息失败！");
					}
				});
			});

			//关闭详情弹窗事件
			$('#detail-factory button.close').click(function() {
				$("#detail_customName").text("");
				$("#detail_facName").text("");
				$("#detail_province").text("");
				$("#detail_city").text("");
				$("#detail_area").text("");
				$("#detail_address").text("");
				$("#detail_zipCode").text("");
			});
			
			//关闭弹窗清空表单内容
			$("#form_btn_close").click(function(){
				$("#customId").empty();
				$("#parentCusId").val("");
				$("#pkId").val("");
				$("#factory_form")[0].reset();
				if (validator) {
					validator.resetForm();
				}
			});
			
			//删除点击
			$("#factory_table_del").on('click', function(){
				var d = [];
				d = util.getCheckedData("factory_table");
				if (d.length == 0) {
					util.showModal("#_alertModal", "请选择要操作的记录！");
				} else {
					util.showModal("#_confirmModal", "您确定要删除选中的记录？", "_confirmModal_yes");
				}
			});
			
			//确认删除
			$("#_confirmModal").on('click', '#_confirmModal_yes', function() {
				var d = [];
				d = util.getCheckedData("factory_table");
				var idArray=[];
				for (var i=0;i<d.length;i++) {
					idArray.push(d[i].pkId);
				}
				var table = $('#factory_table').DataTable();
				var selRows = table.rows('.selected');
				$.ajax({
					"type" : "post",
					"url" : "main/factory/delete.mvc",
					"dataType" : "json",
					"data" : {
						"pkId" : idArray.join(",")
					},
					"success" : function(resp) {
						if (resp.msg == 'packFail') {
							util.showModal("#_alertModal", "已经绑定过电池的厂区不能删除！");
						} else if (resp.msg == 'employeeFail') {
							util.showModal("#_alertModal", "已经关联客户联系人的厂区不能删除！");
						} else {
							rmsBox.notify('success', {msg: '删除成功！'});
							selRows.remove();
							table.draw(true);
						}
					},
					"error" : function(resp) {
						rmsBox.notify('error', {msg: '操作失败！',delay:3000});
					}
				});
			});
			
			//电池关联管理点击事件
			$("#factory_table_tbatteryCorrelation").click(function() {
				var factory = [];
				factory = util.getCheckedData("factory_table");
				if (factory.length != 1) {
					util.showModal("#_alertModal", "请选择一条记录进行电池关联绑定！");
					return false;
				}
				$.ajax({
					"type" : "post",
					"url" : "main/factory/initBatteryCorrelation.mvc",
					"dataType" : "json",
					"data" : {id:factory[0].pkId},
					"success" : function(data) {
						var factory = data.factory;
						var multiSelect = data.multiSelect;
						var i = 0;
						$('<select />', {
							 multiple: "multiple",
							 id: "batteryCorrelation_multiSelect",
							 name: "batteryCorrelation_multiSelect[]"
						}).appendTo($('#multiSelect_controls'));
						$.each(multiSelect,function(index,value){
							var selected = "";
							var enable = "";
							var style = "";
							if (multiSelect[index].selected == 'true') {
								i = i + 1;
								selected = " selected ";
							}
							if (multiSelect[index].enable == 'false') {
								enable = "（报废）";
							}
							$('#batteryCorrelation_multiSelect').append('<option value="' + multiSelect[index].packCode+ '" ' + selected + '>'+multiSelect[index].packCode+ enable +'</option>');
		          		});
						$("#batteryCorrelation_custom").text(factory.custom);
						$("#batteryCorrelation_custom").attr("title", factory.custom);
						$("#batteryCorrelation_packNum").text(i);
						$("#batteryCorrelation_pkId").val(factory.pkId);
						$("#batteryCorrelation_customId").val(factory.customId);
						initMultiSelect("#batteryCorrelation_multiSelect");
						$("#batteryID-correlation").modal({show:true, keyboard:false});
					},
					"error" : function(resp) {
						util.showModal("#_alertModal", "获取该厂区电池关联信息失败！");
					}
				});
			});
			
			//电池绑定注册保存按钮点击事件
			$("#batteryCorrelation_save").click(function() {
				var tmPackCustomFactory = {};
				tmPackCustomFactory['ownerFactory'] = $("#batteryCorrelation_pkId").val();
				tmPackCustomFactory['ownerComp'] = $("#batteryCorrelation_customId").val();
				var packCodeList = $("#batteryCorrelation_multiSelect").val();
				var packCodeStr = "";
				if (!util.isEmpty(packCodeList)) {
					$.each(packCodeList, function(index,value){
						if (index == 0) {
							packCodeStr = packCodeList[index];
						} else {
							packCodeStr += "," + packCodeList[index];
						}
						
	          		});
				}
				tmPackCustomFactory['packCode'] = packCodeStr;
				var table = $('#factory_table').DataTable();
				$.ajax({
					"type" : "post",
					"url" : "main/factory/saveBatteryCorrelation.mvc",
					"dataType" : "json",
					"data" : tmPackCustomFactory,
					"success" : function(resp) {
						$("#batteryCorrelation_close").click();
						table.draw(true);
						rmsBox.notify('success', {msg: '操作成功！'});
					},
					"error" : function(resp) {
						rmsBox.notify('error', {msg: '操作失败！',delay:3000});
					}
				});
			});
			
			//电池绑定注册取消按钮点击事件
			$("#batteryCorrelation_close").click(function() {
				$('#multiSelect_controls').html("");
			});
			//模态框关闭清空多选插件
			$("#batteryID-correlation").on('click', '.close', function(e) {
				e.preventDefault();
				$('#multiSelect_controls').html("");
			});
			
			//初始化两边多选择插件
			function initMultiSelect(selector) {
				$(selector).multiSelect({
				  selectableHeader: "<input type='text' style='width:205px;' autocomplete='off' placeholder='搜索...'>",
				  selectionHeader: "<input type='text' style='width:205px;' autocomplete='off' placeholder='搜索...'>",
				  afterInit: function(ms){
				    var that = this,
				        $selectableSearch = that.$selectableUl.prev(),
				        $selectionSearch = that.$selectionUl.prev(),
				        selectableSearchString = '#'+that.$container.attr('id')+' .ms-elem-selectable:not(.ms-selected)',
				        selectionSearchString = '#'+that.$container.attr('id')+' .ms-elem-selection.ms-selected';
				    that.qs1 = $selectableSearch.quicksearch(selectableSearchString)
				    .on('keydown', function(e){
				      if (e.which === 40){
				        that.$selectableUl.focus();
				        return false;
				      }
				    });

				    that.qs2 = $selectionSearch.quicksearch(selectionSearchString)
				    .on('keydown', function(e){
				      if (e.which == 40){
				        that.$selectionUl.focus();
				        return false;
				      }
				    });
				  },
				  afterSelect: function(){
				    this.qs1.cache();
				    this.qs2.cache();
				  },
				  afterDeselect: function(){
				    this.qs1.cache();
				    this.qs2.cache();
				  }
				});
			}
			
			$(function(){
				$('.search-body .my-input').bind('keyup', function(event) {
					if (event.keyCode == "13") {
						//回车执行查询
						$('.search-button #btn_query').click();
					}
				});
			});
		}
	};
}();

